import { useState,useEffect } from "react";
import { getTopics } from "../api/cnode";

const useTopics = ()=>{
    const [list, setList] = useState([]);
    const [page, setPage] = useState(1);
    const [loading, setLoading] = useState(false);

    useEffect(()=>{
        getTopics({page: page})
            .then(res=>{
                setList([...list, ...res.data]);
                setLoading(false);
            })
            .catch(() => setLoading(false))
    },[page])

    //触底刷新
    const onEndReached = () => {
        console.log(page);
        setPage(page+1);
    }

    // 下拉刷新
    const onRefresh = () => {
        setLoading(true);
        if(page==1){
            getTopics({ page: page })
                .then(res => {
                    setList(res.data);
                })
                .catch(()=>{})
                .finally(() => setLoading(false))
        }else{
            setList([]);
            setPage(1);
        }
        
    }
    return {loading,list,onRefresh,onEndReached}
}
export default useTopics;